import axios  from 'axios';
import { getToken,removeToken } from "utils/auth";
import router from "src/router"
import { ElMessage } from 'element-plus';

const urlMap={
  'dev':'/app-dev',
  'pro':'http://suzhidong.cn/nest-access-api',
}
// http://suzhidong.cn:5000
// process.env.NODE_ENV
class Request   {
   service  = axios.create({
    baseURL: urlMap[process.env.NODE_ENV], // api 的 base_url http://suzhidong.cn:8009
    timeout: 500 // 请求超时时间
  });
  constructor() {
    this.interceptors()
  }
  interceptors() {
    this.service.interceptors.request.use(
      config => {
        if (getToken()) {
          config.headers.token=`${getToken()}`
        }
        console.log('config',config)
        return config
      },
      error => {
        return Promise.reject(error)
      }
    )
    this.service.interceptors.response.use(
    
      response => {
        const status = response.status
        if ((status >= 200 && status < 300) || status === 304) {
          // response.data
          return Promise.resolve(response.data)
        } else {
          if (response.data.code==7001) {
            removeToken();
            router.push({
              path:"/login"
            })
          }
          // 响应错误逻辑处理 5xx 4xx 等等
          return Promise.reject(response)
        }
      },
      error => {
        console.log(this.service)
        // 响应错误逻辑处理
        const response = error.response ;
        const status = response.status
        ElMessage.error(response.data.message)
        if (status==401) {
          removeToken();
          router.push({
            path:"/login"
          })
        }
        console.log(response)
        // this.emit('HttpStatusFaild')
        return Promise.reject(response)
      }
    )
  }
  get(url ,params) {
    return this.service({
      method: 'get',
      url,
      params
    })
  }
  post(url, data) {
    return this.service({
      method: 'post',
      url,
      data
    })
  }
  upload(url, data,config) {
    return this.service({
      method: 'post',
      url,
      data,
      config
    })
  }
  delete(url, data) {
    return this.service({
      method: 'delete',
      url,
      data
    })
  }
  put(url, data) {
    return this.service({
      method: 'put',
      url,
      data
    })
  }
  patch(url, data) {
    return this.service({
      method: 'patch',
      url,
      data
    })
  }
}

const request = new Request()

export default request

